package com.musifind.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.musifind.adapters.LiveUserListAdapter;
import com.musifind.chat.Config;
import com.musifind.chat.ShareExternalServer;
import com.musifind.common.GeneralHelper;
import com.musifind.models.LiveUserItems;
import com.musifind.utils.ImageUtils;
import com.musifind.utils.SessionManager;
import com.musifind.wsclient.objects.Listening;
import com.musifind.wsclient.service.ListeningService;

public class WhoIsListeningWhatActivity extends Activity {

	private ListView lstWhoWhat;
	private LiveUserListAdapter matchAdapter;
	private ArrayList<LiveUserItems> matchArray;
	private ShareExternalServer appUtil;
	private SessionManager session;
	private Button btnRefreshAction;
	Animation animRotate;
	private ProgressDialog progressDialog;
	public int lvGlobalPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_who_what);
		appUtil = new ShareExternalServer();
		session = new SessionManager(getApplicationContext());
		// activity starts as push old activity to left
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

		animRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotation);

		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayShowHomeEnabled(true);
		mActionBar.setDisplayShowTitleEnabled(false);
		LayoutInflater mInflater = LayoutInflater.from(this);
		View mCustomView = mInflater.inflate(R.layout.custom_actionbar_live_users, null);
		btnRefreshAction = (Button) mCustomView.findViewById(R.id.btnRefresh);

		btnRefreshAction.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btnRefreshAction.startAnimation(animRotate);
				new getWhoIsListeningAsyncTask().execute();
			}
		});

		mActionBar.setCustomView(mCustomView);
		mActionBar.setDisplayShowCustomEnabled(true);
		final int actionBarColor = getResources().getColor(R.color.ActionBarDark);
		mActionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

		matchArray = new ArrayList<LiveUserItems>();
		matchAdapter = new LiveUserListAdapter(WhoIsListeningWhatActivity.this, R.layout.live_user_list_items_row,
				matchArray);
		lstWhoWhat = (ListView) findViewById(R.id.lstWhoIsListeningWhat);
		lstWhoWhat.setAdapter(matchAdapter);

		new getWhoIsListeningAsyncTask().execute();

		lstWhoWhat.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				lvGlobalPosition = position;
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WhoIsListeningWhatActivity.this);
				alertDialogBuilder.setTitle("Uyarı").setMessage("Ne yapmak istiyorsunuz?").setCancelable(true)
						.setPositiveButton("Eşleş", new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								LiveUserItems sItem = matchAdapter.getItem(lvGlobalPosition);
								sendMatchingRequestToGCMAppServer(Config.ACTION_MATCH_ISTEK, sItem.getGcmRegId(),
										session.getUsername(), sItem.getTrackId(), sItem.getTrackName(),
										sItem.getArtistName(), String.valueOf(session.getUserId()));
								dialog.dismiss();
							}
						}).setNegativeButton("Geri", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

								dialog.cancel();
							}

						});

				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			}
		});

	}

	public class getWhoIsListeningAsyncTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(WhoIsListeningWhatActivity.this);
			progressDialog.setTitle("Yükleniyor");
			progressDialog.setMessage("Lütfen bekleyiniz...");
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			runOnUiThread(new Runnable() {
				public void run() {
					matchArray.clear();
					ListeningService listeningService = new ListeningService();
					List<Listening> listenings = listeningService.getWhoIsListeningWhat();
					for (Listening listening : listenings) {
						Bitmap image = ImageUtils.getBitmap(listening.getKullanici().getImage()) == null ? GeneralHelper
								.drawableToBitmap(getResources().getDrawable(R.drawable.pp_facebook)) : ImageUtils
								.getBitmap(listening.getKullanici().getImage());
						matchArray.add(new LiveUserItems(GeneralHelper.roundCornerImage(image, 120), listening
								.getTrackId(), listening.getKullanici().getAd() + " "
								+ listening.getKullanici().getSoyad(), listening.getTrackName(), listening
								.getArtistName(), listening.getKullanici().getGcmRegId(), String.valueOf(session
								.getUserId())));

						// GeneralHelper.roundCornerImage(
						// GeneralHelper.drawableToBitmap(getResources().getDrawable(
						// R.drawable.pp_facebook)), 120), listening.getTrackId(),
						// listening.getKullanici().getAd() + " " + listening.getKullanici().getSoyad(),
						// listening.getTrackName(), listening.getArtistName()));
					}
					matchAdapter.notifyDataSetChanged();
				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(String s) {
			progressDialog.dismiss();
		}
	}

	// to send message to another device via Google GCM
	private void sendMatchingRequestToGCMAppServer(final String action, final String toRegId,
			final String fromUserName, final String trackId, final String trackName, final String artistName,
			final String fromUserId) {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String result = appUtil.sendMessage(action, session.getGCMRegistrationId(), toRegId, fromUserName,
						trackId, trackName, artistName, fromUserId, null, null);
				Log.d("MainActivity", "Result: " + result);
				return result;
			}

			@Override
			protected void onPostExecute(String msg) {
				Log.d("MainActivity", "Result: " + msg);
				GeneralHelper.showPurpleToast(getApplicationContext(), msg);
			}
		}.execute(null, null, null);
	}

}
